import { Component } from "react";
import { Button } from "antd";
import TestView from "@/components/TestView";

interface PropsType {
    name: string,
    logMessage: Function
}
interface myObjectType {
    obj1: string,
    obj2: string
}
interface StateType {
    count: number,
    testName: string,
    myObject: myObjectType
}

class Page2 extends Component<PropsType, StateType> {

    // 构造函数
    constructor(props: PropsType) {
        super(props)
        this.state = {
            count: 2,
            testName: 'chen',
            myObject: {
                obj1: 'value1',
                obj2: 'value2'
            }
        }
    }

    // 组件挂载之后调用
    componentDidMount() {
        console.log('Component mounted');
        console.log('Props=', this.props)
    }

    // 组件更新之后调用
    componentDidUpdate(prevProps: PropsType, prevState: StateType) {
        console.log('prevProps=', prevProps)
        console.log('prevState=', prevState)
        if (prevState.count !== this.state.count) {
            console.log('Component updated');
        }
        if(prevState.myObject.obj1 !== this.state.myObject.obj1) {
            console.log('最新的对象', this.state.myObject)
        }
    }

    // 组件卸载前调用
    componentWillUnmount() {
        console.log('Component will unmount');
    }

    increment = () => {
        this.setState({ count: this.state.count + 1 });
    };

    testLog = () => {
        this.props.logMessage('触发了传递过来的Event')
    }

    // 测试组件传递事件
    changeTestName = (valueName: string) => {
        this.setState({ testName: valueName });
    }

    // 改变对象
    changeObj = () => {
        this.setState(prevState => ({
            myObject: {
              ...prevState.myObject,
              obj1: 'newValue1',
            },
          }));
    }

    // reder函数
    render() {
        return (
            <>
                <div>Page2</div>
                <br />
                <p>{this.state.count}</p>
                <p>{this.props.name}</p>
                <hr />
                <button onClick={this.increment}>Increment</button>
                <br />
                <Button style={{marginTop: '10px'}} type="primary" onClick={this.testLog}>Test Props Events</Button>
                <hr />
                <TestView name={this.state.testName} changeName={this.changeTestName}></TestView>
                <hr />
                <Button onClick={this.changeObj}>changeObj</Button>
            </>
        )
    }
}

export default Page2